package com.itheima.tlias.controller;

import com.github.pagehelper.Page;
import com.itheima.tlias.pojo.Emp;
import com.itheima.tlias.pojo.PageResult;
import com.itheima.tlias.pojo.Result;
import com.itheima.tlias.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

//学院管理控制器
@RestController
@RequestMapping("/emps")
@Slf4j
public class EmpController {
    @Autowired
    EmpService empService;

    @GetMapping("/list")
    public Result findAll() {
        return Result.success(empService.findAll());
    }

    ///emps?name=张&gender=1&begin=2007-09-01&end=2022-09-01&page=1&pageSize=10
    @GetMapping
    public Result findSomeEmp(String name,
                              Integer gender,
                              @RequestParam(defaultValue = "1970-01-01")
                              @DateTimeFormat(pattern = "yyyy-MM-dd") Date begin,
                              @RequestParam(defaultValue = "2050-01-01")
                              @DateTimeFormat(pattern = "yyyy-MM-dd") Date end,
                              @RequestParam(defaultValue = "1") int page,
                              @RequestParam(defaultValue = "10") int pageSize) {

        Emp emp = Emp.builder().name(name).gender(gender).build();

        // 获取分页数据
        List<Emp> rows = empService.findSomeEmp(emp, begin, end, page, pageSize);
        // 获取总记录数
        Long total = ((Page)rows).getTotal();
        // 构建分页结果
        return Result.success(new PageResult(total, rows));
    }
    // 删除员工
    @DeleteMapping
    public Result delete( Integer... ids) {
        int row = empService.delete(ids);
        if (row > 0) {
            return Result.success();
        }
        return Result.error("删除失败");
    }

     //新增员工
    @PostMapping
    public Result insert(@RequestBody Emp emp){
        if (empService.insert(emp)> 0) {
            return Result.success();
        }
        return Result.error("添加失败");
    }

    //修改员工操作
    //根据id回显数据
    @GetMapping("/{id}")
    public Result findById(@PathVariable("id") Integer id) {
        if (id > 0) {
            Emp emp = empService.findById(id);
            return Result.success(emp);
        }
        return Result.error("查询失败");
    }

    @PutMapping
    public Result update(@RequestBody Emp emp) {
        if (empService.update(emp) > 0) {
            return Result.success();
        }
        return Result.error("修改失败");
    }


}





